package com.achao.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: achao
 * @DateTime: 2022/10/16 12:22
 * @Description: TODO
 */
@Component
public class GlobalBlockException implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, BlockException e) throws Exception {
        String str = "null";
        if (e instanceof FlowException) {
            str = "接口被限流了";
        } else if (e instanceof DegradeException) {
            str = "服务降级了";
        } else if (e instanceof ParamFlowException) {
            str = "热点参数限流了";
        } else if (e instanceof SystemBlockException) {
            str = "触发系统保护规则";
        } else if (e instanceof AuthorityException) {
            str = "授权规则不通过";
        }

        resp.setStatus(500);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(resp.getWriter(),str);

    }
}
